package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: OrderTask
 *
 * @AUTHOR: zhang
 * DATE: 2024/1/22
 * DESCRIPTION :定时处理超时未支付的订单/状态一致为派送中的订单
 */

@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrdersMapper ordersMapper;


    /**
     * 定时处理超时未支付的订单
     */
    @Scheduled(cron = "0 * * * * * ") //每分钟执行
    public void processUnpaidOrders(){
        log.info("定时处理超时未支付的订单，{}",LocalDateTime.now());
        //获取下单时间为15分钟前的时间
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        //查询状态为未支付下单时间小于当前时间15分钟的订单
        List<Orders> orders = ordersMapper.selectOvertimeAndUnpaidOrders(Orders.PENDING_PAYMENT,orderTime);
        if (orders!=null && orders.size() > 0){
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时，已取消！");
                ordersMapper.updateOrders(order);
            }
        }
    }

    /**
     * 定时处理昨天订单状态一致为派送中的订单为已完成
     */
    @Scheduled(cron = "0 0 1 * * ?  ")//每天凌晨1点执行
    public void processDeliveryInProgressOrders(){
        log.info("定时处理超时未支付的订单，{}",LocalDateTime.now());
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(60);
        //查询订单状态为派送中的订单
        List<Orders> ordersList = ordersMapper.selectOvertimeAndUnpaidOrders(Orders.DELIVERY_IN_PROGRESS,orderTime);
        if (ordersList!=null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                ordersMapper.updateOrders(orders);
            }
        }
    }
}
